// cloudfunctions/deleteUnpaidExpiredOrders/index.js
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command
const MAX_BATCH_SIZE = 100 // 最大批量处理数量

// 云函数入口函数
exports.main = async (event, context) => {
    try {
        console.log('开始执行删除过期未付款订单任务', event);

        // 从参数获取配置，设置默认值
        const {
            expireDays = 1, // 过期天数，默认1天
                orderStatus = 1, // 未付款订单状态码，默认1
                batchSize = MAX_BATCH_SIZE // 批量处理数量，默认100
        } = event;
        // 3. 统计符合条件的订单数量
        const countResult = await db.collection('orders')
            .where({
                status: orderStatus, // 未付款状态
                // createTime: expireTimeISO// 创建时间早于过期时间
            })
            .count();

        const totalExpiredOrders = countResult.total;
        console.log(`找到 ${totalExpiredOrders} 条过期未付款订单`);

        if (totalExpiredOrders === 0) {
            return {
                success: true,
                message: '没有找到过期未付款订单',
                data: {
                    totalExpiredOrders,
                    expireDays,
                    orderStatus,
                    processTime: 0
                }
            };
        }

        // 4. 分页删除订单
        let deletedCount = 0;
        let page = 0;
        const startTime = new Date();

        while (deletedCount < totalExpiredOrders) {
            // 计算本次查询的偏移量
            const skip = page * batchSize;
            const limit = Math.min(batchSize, totalExpiredOrders - deletedCount);

            // 查询符合条件的订单
            const queryResult = await db.collection('orders')
                .where({
                    status: orderStatus,
                })
                .orderBy('createTime', 'asc')
                .skip(skip)
                .limit(limit)
                .get();
            console.log(queryResult);
            const orders = queryResult.data;
            if (orders.length === 0) break;

            // 收集订单ID
            const orderIds = orders.map(order => order._id);
            console.log(`第 ${page + 1} 页，正在删除 ${orders.length} 条订单...`);

            // 批量删除订单（使用事务确保一致性）
              const transaction = await db.startTransaction();
              try {
                const deleteResult = await transaction.collection('orders')
                  .where({ _id: _.in(orderIds) })
                  .remove();

                await transaction.commit();
                deletedCount += deleteResult.stats.deleted;
                console.log(`成功删除 ${deleteResult.stats.deleted} 条订单`);

              } catch (txError) {
                console.error('事务处理失败:', txError);
                await transaction.rollback();
                throw new Error(`事务处理失败，已回滚，错误: ${txError.message}`);
              }

            page++;
        }

        // 5. 记录操作日志
        await db.collection('operation_logs').add({
            data: {
                action: 'delete_unpaid_expired_orders',
                params: {
                    expireDays,
                    orderStatus,
                    batchSize,
                    totalExpiredOrders
                },
                deletedCount,
                operateTime: new Date(), // 使用本地时间记录操作时间
                duration: new Date() - startTime,
                remark: `删除状态为${orderStatus}且创建时间超过${expireDays}天的未付款订单，共删除${deletedCount}条`
            }
        });

        console.log(`删除过期未付款订单任务完成，共删除 ${deletedCount} 条记录，耗时 ${new Date() - startTime}ms`);
        return {
            success: true,
            message: `成功删除 ${deletedCount} 条过期未付款订单`,
            data: {
                deletedCount,
                totalExpiredOrders,
                expireDays,
                orderStatus,
                processTime: new Date() - startTime
            }
        };

    } catch (error) {
        console.error('删除过期未付款订单任务失败:', error);
        // 记录详细错误日志
        await db.collection('error_logs').add({
            data: {
                errorType: 'delete_unpaid_expired_orders',
                errorMessage: error.message,
                errorStack: error.stack,
                params: event,
                occurTime: new Date() // 使用本地时间记录错误时间
            }
        });

        return {
            success: false,
            message: '删除过期未付款订单任务失败',
            error: {
                message: error.message,
                stack: error.stack
            }
        };
    }
};